<template>
  <div class="app-container">
    <div
      class="header"
      style="display: flex; justify-content: space-between"
    >
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item>
          <el-button
            icon="refresh"
            color=" rgb(69, 76, 105)"
            style="color: #fff"
            @click="resetQuery()"
          />
        </el-form-item>
      </el-form>
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item
          label=""
          prop=""
        >
          <el-cascader
            :props="props"
            v-model="location"
            placeholder="请选择区域名称（省-市-区）"
            @keyup.enter="handleQuery"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="info"
            icon="Search"
            @click="handleQuery()"
          />
        </el-form-item>
      </el-form>
    </div>

    <el-table
      v-loading="loading"
      :data="zoneList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="省"
        align="center"
        prop="province"
      />
      <el-table-column
        label="市"
        align="center"
        prop="city"
      />
      <el-table-column
        label="区/县"
        align="center"
        prop="zone"
      />
      <el-table-column
        label="新人优惠券发布数量"
        align="center"
        prop="publishNum"
      />
      <el-table-column
        label="新人优惠券发放金额"
        align="center"
        prop="publishAmount"
      />
      <!-- <el-table-column
        label="新人优惠券发放状态"
        align="center"
        prop="publishState"
      /> -->

      <!-- 加入的 -->
      <el-table-column
      label="新人优惠券发放状态"
      align="center"
    >
      <template v-slot="{ row }">
        <span>
          {{row.publishState == '0' ? '发放' : '未发放'}}
        </span>
      </template>
    </el-table-column>


      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:zone:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleArea(scope.row)"
            v-hasPermi="['system:zone:edit']"
            >电子栅栏{{ scope.row.coordinate ? "查看" : "编辑" }}</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:zone:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :title="title"
      v-model="openArea"
      width="1500px"
      append-to-body
      @close="cancelArea"
    >
      <el-form
        ref="zoneRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="绘制区域"
          prop=""
        >
          <div
            id="mapRef"
            class="map_container"
            ref="mapRef"
            style="width: 1500px; height: 750px"
          ></div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitFormArea"
            >确 定</el-button
          >
          <el-button @click="cancelArea">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改区域管理对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="zoneRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="省"
          prop="province"
        >
          <el-input
            v-model="form.province"
            placeholder="请输入省"
          />
        </el-form-item>
        <el-form-item
          label="市"
          prop="city"
        >
          <el-input
            v-model="form.city"
            placeholder="请输入市"
          />
        </el-form-item>
        <el-form-item
          label="区/县"
          prop="zone"
        >
          <el-input
            v-model="form.zone"
            placeholder="请输入区/县"
          />
        </el-form-item>
        <el-form-item
          label="发布数量"
          prop="publishNum"
        >
          <el-input
            v-model="form.publishNum"
            placeholder="请输入发布数量"
          />
        </el-form-item>
        <el-form-item
          label="发放金额"
          prop="publishAmount"
        >
          <el-input
            v-model="form.publishAmount"
            placeholder="请输入发放金额"
          />
        </el-form-item>
        <!-- <el-form-item
          label="发放状态"
          prop="publishState"
        >
          <el-input
            v-model="form.publishState"
            placeholder="请输入发放状态 0(发放) 1(未发放)" 
          />
        </el-form-item>
        <el-form-item
          label="抢单类型"
          prop="model"
        >
          <el-input
            v-model="form.model"
            placeholder="请输入抢单类型"
          />
        </el-form-item>
        <el-form-item
          label="坐标数组"
          prop="coordinate"
        >
          <el-input
            v-model="form.coordinate"
            placeholder="请输入坐标数组"
          />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Zone">
import {
  listZone,
  getZone,
  delZone,
  addZone,
  updateZone,
  getZoneCoordinate,
} from "@/api/system/zone";
import { getRegionChildren } from "@/api/system/rules";
import { ref } from "vue";
import axios from "axios";

const { proxy } = getCurrentInstance();

const zoneList = ref([]);
const open = ref(false);
const openArea = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const coordinate = ref([]);
const code = ref(0);
const location = ref();
const props = ref({
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    if (level > 0) code.value = node.data.code;
    getRegionChildren(code.value).then((res) => {
      const nodes = [];
      for (let i = 0; i < res.data.length; i++) {
        nodes.push({
          value: res.data[i].name,
          label: res.data[i].name,
          leaf: level >= 2,
          code: res.data[i].code,
        });
      }
      resolve(nodes);
    });
  },
});

const data = reactive({
  form: {
    coordinate: [],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    province: null,
    city: null,
    zone: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);
var map;

function checkMap(position, addr) {
  var dataMap = {
    key: "KSNBZ-CA435-ML4IW-IB6HF-ZRVPZ-JGB5W",
    address: addr,
  };
  const fetchGeocode1 = async () => {
    try {
      const response = await axios.get("/ts/ws/geocoder/v1", {
        params: dataMap,
      });
      const res = response.data.result;
      map = new TMap.Map("mapRef", {
        zoom: 12, // 设置地图缩放级别
        center: new TMap.LatLng(res.location.lat, res.location.lng), // 设置地图中心点坐标
        viewMode: "2D",
      });

      var data = [];
      for (let i = 0; i < position.length; i++) {
        var path = [];
        for (let j = 0; j < position[i].length; j++) {
          path.push(new TMap.LatLng(position[i][j].lat, position[i][j].lng));
        }
        data.push({
          id: `p${i}`, //该多边形在图层中的唯一标识（删除、更新数据时需要）
          styleId: `polygon${i}`, //绑定样式名
          paths: path, //多边形轮廓
        });
      }

      var polygon = new TMap.MultiPolygon({
        id: "polygon-layer", //图层id
        map: map, //设置多边形图层显示到哪个地图实例中
        //多边形样式
        styles: {
          polygon: new TMap.PolygonStyle({
            color: "#3777FF", //面填充色
            showBorder: false, //是否显示拔起面的边线
            borderColor: "#00FFFF", //边线颜色
          }),
        },
        //多边形数据
        geometries: data,
      });
    } catch (error) {
      console.error("Error fetching geocode data:", error);
    }
  };
  fetchGeocode1();
  openArea.value = true;
}

function initMap(addr) {
  var dataMap = {
    key: "KSNBZ-CA435-ML4IW-IB6HF-ZRVPZ-JGB5W",
    address: addr,
  };
  const fetchGeocode = async () => {
    try {
      const response = await axios.get("/ts/ws/geocoder/v1", {
        params: dataMap,
      });
      const res = response.data.result;
      map = new TMap.Map("mapRef", {
        zoom: 12, // 设置地图缩放级别
        center: new TMap.LatLng(res.location.lat, res.location.lng), // 设置地图中心点坐标
        viewMode: "2D",
      });

      // 初始化几何图形及编辑器
      var editor = new TMap.tools.GeometryEditor({
        map, // 编辑器绑定的地图对象
        overlayList: [
          // 可编辑图层
          {
            //GeometryEditor 以 MultiPolygon（可以理解为多边形图层）激活进行编辑
            id: "polygon133",
            overlay: new TMap.MultiPolygon({
              map,
            }),
          },
        ],
        actionMode: TMap.tools.constants.EDITOR_ACTION.DRAW, //编辑器的工作模式
        snappable: true, // 开启邻近吸附
      });

      map.on("destroy", function () {
        console.log("地图已销毁");
      });
      // 监听绘制结束事件，获取绘制几何图形
      editor.on("draw_complete", (geometry) => {
        coordinate.value.push(geometry.paths);
      });
    } catch (error) {
      console.error("Error fetching geocode data:", error);
    }
  };
  fetchGeocode();
  openArea.value = true;
}

/** 查询区域管理列表 */
function getList() {
  loading.value = true;
  listZone(queryParams.value).then((response) => {
    console.log(response, "respo区域管理返回的数据");
    zoneList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  form.value = {};
}

function cancelArea() {
  map.destroy();
  openArea.value = false;
  form.value = {};
}

// 表单重置
function reset() {
  form.value = {
    zoneId: null,
    province: null,
    city: null,
    zone: null,
    publishNum: null,
    publishAmount: null,
    publishState: null,
    model: null,
    coordinate: [],
  };
  proxy.resetForm("zoneRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  if (location.value && location.value.length == 3)
    queryParams.value.location = location.value.join("");
  else queryParams.value.location = "";
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.zoneId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加区域管理";
}

function handleArea(row) {
  form.value = row;
  var addr = row.province + row.city + row.zone;
  if (!row.coordinate) initMap(addr);
  else {
    coordinate.value = JSON.parse(row.coordinate);
    checkMap(coordinate.value, addr);
  }
  title.value = "电子栅栏编辑";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _zoneId = row.zoneId || ids.value;
  getZone(_zoneId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改区域管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["zoneRef"].validate((valid) => {
    if (valid) {
      if (form.value.zoneId != null) {
        updateZone(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addZone(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function submitFormArea() {
  proxy.$refs["zoneRef"].validate((valid) => {
    if (valid) {
      form.value.coordinate = JSON.stringify(coordinate.value);
      updateZone(form.value).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        openArea.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _zoneIds = row.zoneId || ids.value;
  proxy.$modal
    .confirm('是否确认删除区域管理编号为"' + _zoneIds + '"的数据项？')
    .then(function () {
      return delZone(_zoneIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/zone/export",
    {
      ...queryParams.value,
    },
    `zone_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
